package day6;

import java.util.*;
class CartItem {
    private int count;      // 购买数量
    private int totalPrice; // 总价
    public CartItem(int price) {
        this.count = 1;
        this.totalPrice = price;
    }
    // 增加商品数量
    public void addItem(int price) {
        this.count++;
        this.totalPrice += price;
    }
    public int getCount() {
        return count;
    }
    public int getTotalPrice() {
        return totalPrice;
    }
}
public class Demo1 {
    public static void main(String[] args) {
        Map<String, CartItem> cart = new HashMap<>();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入商品名称和单价（输入'结束'完成输入）：");
        while (true) {
            System.out.print("商品名称：");
            String name = scanner.next();
            if (name.equals("结束")) break;
            System.out.print("单价：");
            int price = scanner.nextInt();
            if (cart.containsKey(name)) {
                cart.get(name).addItem(price);
            } else {
                cart.put(name,new CartItem(price));
            }
        }
        System.out.println("\n商品名称   个数   总价");
        int grandTotal = 0;
        for (Map.Entry<String,CartItem> entry:cart.entrySet()) {
            String name = entry.getKey();
            CartItem item = entry.getValue();
            System.out.printf( "%-8s   %-4d   %-4d%n",name,item.getCount(),item.getTotalPrice());
            grandTotal += item.getTotalPrice();
        }
        System.out.println("\n总价: " + grandTotal);
    }
}